<template>
  <div class="graph-column graph-column-box">
    <div id="groups" class="column" :class="{'droping': echartDrag.originName}" @drop='dropChart($event)' @dragover='allowDrop($event)'  >
      <div class="title f-l">
        <span class="rounds"></span>
        <span class="f-l">维度</span>
      </div>
      <ul class="f-l">
        <li v-for="(item,index) in groups" :key="index" draggable="true"  @dragstart="cloumnMoveStart('groups',index,$event)">
            <column-item :groupOptions="GROUP_OPTIONS" v-model="groups[index]">
                <span class="cloumntit">{{item.columnName}}
                  <template v-if="item.aggregationName!=null">({{item.aggregationName}})</template>
                </span>
                <span slot="last" class="pointer close" @click="removeGroup(index)">
                  <i class="zlstbd-icon-delete"></i>
                </span>
            </column-item>
        </li>
      </ul>
    </div>
    <div id="nums" class="column m-b-10" :class="{'droping': echartDrag.originName}" @drop='dropChart($event)' @dragover='allowDrop($event)' >
      <div class="title f-l">
        <i class="rounds"></i>
        <span>数值</span>
      </div>
      <ul class="">
        <li v-for="(item,index) in numbers" :key="index" draggable="true"   @dragstart="cloumnMoveStart('nums',index,$event)">
          <column-item :groupOptions="dataType.int.indexOf(item.dataType)!=-1?NUM_OPTIONS:TEXT_OPTIONS" v-model="numbers[index]" >
            <span class="cloumntit">{{item.columnName}}
              <template v-if="item.aggregationName!=null">({{item.aggregationName}})</template>
            </span>
            <span slot="last" class="pointer close" @click="removeNums(index)"> <i class="zlstbd-icon-delete"></i></span>
          </column-item>
        </li>
      </ul>
    </div>
  </div>
</template>
<script type="text/javascript">
import util from 'util';
import ColumnItem from '@/pages/ui-editor/header/column-item'
import emitter from '@/mixins/emitter';

export default {
  components: {
    ColumnItem
  },
  data () {
    return {
      groups: [],
      numbers: [],
      conditions: [],
      dataType:{
        int:'int,float,double',
        data:'date,timestamp'
      },
      NUM_OPTIONS:[
        {
          value:'aggregation',
          options:[
            {value: 'SUM',label: '求和'},
            {value: 'AVG',label: '平均值'},
            {value: 'COUNT',label: '计数'},
            {value: 'COUNT_DISTINCT',label: '去重计数'},
            {value: 'MAX',label: '最大值'},
            {value: 'MIX',label: '最小值'}
          ]
        },
        {
          value:'sort',
          options:[
            {value: 'ASC',label: '升序'},
            {value: 'DESC',label: '降序'},
          ]
        }
      ],
      TEXT_OPTIONS:[
        {
          value:'aggregation',
          options:[
            {value: 'COUNT',label: '计数'},
            {value: 'COUNT_DISTINCT',label: '去重计数'},
          ]
        },
        {
          value:'sort',
          options:[
            {value: 'ASC',label: '升序'},
            {value: 'DESC',label: '降序'},
          ]
        }
      ],
      GROUP_OPTIONS:[
        {
          value:'sort',
          options:[
            {value: 'ASC',label: '升序'},
            {value: 'DESC',label: '降序'},
          ]
        }
      ],
      // 用于删除后恢复
      graphOptionBak: {
        xAxis: [],
        yAxis: []
      }
    }
  },
  props: {
    uiItemList: {
      type: Array,
      default: function() {
        return []
      }
    },
    selectedIndex: {
      type: [Number, String]
    },
    echartDrag: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  methods: {
    dropChart(ev){
      // 1. 判断是数值还是维度
      var cloum ,index=-1,$dom,$cloum;
      for(var i=0;i<ev.path.length;i++){
        if(ev.path[i].id=='nums'){
          cloum="nums";
          $cloum=ev.path[i];
        }else if(ev.path[i].id=='groups'){
          cloum='groups';
          $cloum=ev.path[i];
        }
        if( ev.path[i].className ==='group-menu'){
          $dom=ev.path[i];
        }
      }
      if($dom!=null){
        var $list =$cloum.querySelectorAll('.group-menu');
        for(var i =0 ;i<$list.length;i++){
          if($list[i]==$dom){
            index=i+'';
          }
        }
      }

      if(this.echartDrag.originName){
          //1左侧 字段 新增
          var item = util.util.cloneObj(this.echartDrag);
          if(cloum=='nums'){
            if(this.dataType.int.indexOf(item.dataType)!=-1){
              item.aggregation="SUM";
              item.aggregationName="求和";
            }else {
              item.aggregation="COUNT";
              item.aggregationName="计数";
            }
            if(util.util.getArrayObjectByValues(this.numbers,item,'columnId')==null){
              this.numbers.push(item);
            }else{
              this.$Message.error('该字段已经在筛选列表里，请勿重复添加')
            }
          }else if(cloum=='groups'  && this.groups.length<2){
            if(util.util.getArrayObjectByValues(this.groups,item,'columnId')==null){
              this.groups.push(item);
            }else{
              this.$Message.error('该字段已经在筛选列表里，请勿重复添加')
            }
          }
      }else {
          //2维度和数据   改变位置
          var moveIndex =ev.dataTransfer.getData("index");
          var mtype  =ev.dataTransfer.getData("moveType");
          if( mtype==cloum && moveIndex!==index){
              var list =cloum=='nums'?this.numbers:this.groups;
              if(index<0){//没有选择
                  index=list.length-1;
              }
              var good=list[moveIndex];
              var goodo=list[index];
              list.splice(moveIndex,1,goodo);
              list.splice(index,1,good);
          }
      }
    },
    allowDrop(ev){
        ev.preventDefault();
    },
    cloumnMoveStart(type,index,ev){
        this.moveType='cloumn';
        ev.dataTransfer.setData("index",index);
        ev.dataTransfer.setData("moveType",type);
    },
    removeNums(index){
      this.isNumberChange = true
      this.numbers.splice(index,1);
      // this.getDimension()
    },
    removeGroup(index){
      this.groups.splice(index,1)
    },
    judgeGraphType(){
      let types =[], type ='';
      if(this.groups.length > 0 || this.numbers.length > 0){
        types = types.concat(['table', 'text', 'img'])
        type ='pie';
      }
      if(this.groups.length === 2 && this.numbers.length === 0){
        types = types.concat(['bar', 'bar_type', 'line'])
        type ='bar';
      }
      if(this.groups.length === 0 && this.numbers.length === 1){
        types.push('gauge');
      }
      if(this.groups.length<=2 && this.numbers.length>=1){
        types = types.concat(['bar', 'bar_type', 'pie_more'])
        type ='bar';
      }
      if(this.groups.length > 0 && this.groups.length <= 2 && this.numbers.length >= 1){
        types = types.concat(['line', 'line_area'])
        type ='line';
      }
      if(0 < this.groups.length && this.groups.length <= 2 && this.numbers.length >= 2){
        types = types.concat(['bar_pile', 'bar_type_pile'])
      }
      if(this.groups.length === 1 && this.numbers.length === 2){
        types.push('scatter');
      }
      if(this.groups.length === 1 && this.numbers.length === 0){
        types.push('pie');
      }
      if((this.groups.length === 1 && this.numbers.length === 1) || (this.groups.length === 0 && this.numbers.length >= 1)){
        types = types.concat(['pie', 'funnel'])
      }
      if(this.groups.length >= 1 && this.numbers.length <= 1){
        types.push('tree');
      }
      if(this.groups.length === 1 && this.numbers.length >= 1){
        types.push('map');
      }
      if (this.groups.length >= 0 && this.numbers.length === 1) {
        types.push('card');
      }
      //在当前可以选择的 图表类型  当前默认选择的图表类型
      // if(this.groupNumLock){
      //     return ;
      // }
      // emitter.methods.dispatch('MainBoard', 'widget-graph-type', {supportTypes: types, type: type}, this)
      this.setGraphOptionsByType({supportTypes: types, type: type})
    },
    setGraphOptionsByType(graphInfo) {
      console.log('setGraphOptionsByType: ' + graphInfo.type)
      let setting = this.uiItemList[this.selectedIndex]
      let options = setting.graphOptions
      if (graphInfo.type === 'bar') {
        // 条形图
        let series = []
        for (let i = 0; i < options.series.length; i++) {
          series.push({
            type: 'bar',
            barWidth: ''
          })
        }
        this.changeOptions({key:'series',value:series}, graphInfo)
      } else if (['funnel', 'pie', 'pie_more'].indexOf(graphInfo.type) !== -1) {
        // 漏斗图
        let series = []
        for (let i = 0; i < options.series.length; i++) {
          if (graphInfo.type === 'funnel') {
            series.push({
              type: 'funnel',
              label: {
                show: true,
                position: 'inside'
              },
              labelLine: {
                show: false
              }
            })
          } else if (graphInfo.type === 'pie') {
            series.push({
              type: 'pie',
              label: {
                show: true,
                position: ''
              },
              labelLine: {
                show: true
              }
            })
          } else if (graphInfo.type === 'pie_more') {
            series.push({
              type: 'pie',
              label: {
                show: true,
                position: ''
              },
              labelLine: {
                show: true
              },
              radius: ['50%', '70%']
            })
          }
        }
        let color = []
        if (options.dataset && Array.isArray(options.dataset)) {
          let source = options.dataset[0].source
          if (source && source.length > 0) {
            for (let i = 0; i < source.length; i++) {
              color.push('#90c4d2')
            }
          }
        }
        let optionsNew = Object.assign({color: color}, options)
        optionsNew.series = series
        this.graphOptionBak.xAxis = [].concat(optionsNew.xAxis)
        this.graphOptionBak.xAxis = [].concat(optionsNew.yAxis)
        delete optionsNew.xAxis
        delete optionsNew.yAxis
        this.changeOptions(optionsNew, graphInfo)
      } else {
        !options.xAxis && (options.xAxis = this.graphOptionBak.xAxis)
        !options.yAxis && (options.yAxis = this.graphOptionBak.yAxis)
        this.changeOptions(options, graphInfo)
      }
    },
    changeOptions(item, graphInfo){
      // 1. 改变 graphOptions
      var value, graphOptionsRet;
      let setting = this.uiItemList[this.selectedIndex]
      if(item.key !== null){
        let graphOptions = item
        if(item.key === 'xAxis'){
          value = util.util.cloneObj(graphOptions[item.key]);
          util.util.extendObj(value[0],item.value);
        }else{
          // 进入其他 others 图表类型
          value = util.util.cloneObj(graphOptions[item.key]);
          util.util.extendObj(value,item.value);
        }
        var options = util.util.cloneObj(graphOptions)
        options[item.key]= value
        graphOptionsRet= options;
      }else{
        graphOptionsRet= item;
      }
      // 2. 改变datasource
      var source = {};
      source.datasourceId = setting.dataSource.datasourceId;
      source.datasourceType = setting.dataSource.datasourceType;
      source.tableName = setting.dataSource.tableName;
      source.groups = [].concat(this.groups);
      source.numbers = [].concat(this.numbers);
      source.conditions = this.conditions;
      emitter.methods.dispatch('MainBoard', 'widget-chart', {graphOptions: graphOptionsRet, dataSource: source, graphInfo: graphInfo}, this)
    }
  },
  watch:{
    numbers:  {
      handler() {
        this.judgeGraphType();
　　　　},
　　　　deep: true
　　},
    groups:{
      handler() {
        this.judgeGraphType();
      },
      deep: true
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>

</style>
